A combinator is something that explains the relationship between the selectors.
A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.
There are four different combinators in CSS:
The descendant selector matches all elements that are descendants of a specified element.
Example
Example
The following example selects all <p> elements inside <div> elements:
div p {
background-color: yellow;
}
In this page
.middle h2{
color: brown;
text-align: left;
}
The child selector selects all elements that are the children of a specified element.
Example
The following example selects all <p> elements that are children of a <div> element:p
div > p {
background-color: yellow;
}
In this page
code > pre > p{
color: rgb(71, 15, 124);
text-decoration: underline;
}
The adjacent sibling selector is used to select an element that is directly after another specific element.
Sibling elements must have the same parent element, and "adjacent" means "immediately following".
Example
The following example selects the first <p> element that are placed immediately after <div> elements:
div + p {
background-color: yellow;
}
In this page
.adjacente-example + p{
background-color: yellow;
}
Paragraph 1 in the adjacente-example.
Paragraph 2 in the adjacente-example.
Paragraph after the adjacente-example.
The general sibling selector selects all elements that are next siblings of a specified element.
Example
The following example selects all <p> elements that are next siblings of <div> elements:
div ~ p {
background-color: yellow;
}
In this page
.head2 ~ th {
background-color: #9947e6;
}
.div-inner ~ p{
background-color: yellow;
}
Paragraph 1.
Paragraph 2.
Paragraph 3.
Some code.
Paragraph 4.
Head1 | Head2 | Head3 |
---|---|---|
Data1 | Data2 | Data3 |
The comma permit setting lots of elemnets, with the same properties.
Example
The following example get <p> and <div> the same color:
div, p {
background-color: yellow;
}
In this page
.head2 ~ th {
background-color: #9947e6;
}
.div-inner ~ p{
background-color: yellow;
}
To select an element with two clases we need to apeend a class to another class.
Example
The following example get the element with the class ".title2" ".container", its mean 'class="title2 container"':
.title2.container{
background-color: yellow;
}
In this page
.red.border{
border: 1px #000 solid;
background-color: red;
}
I have the clases .red and .tex-black